package com.example.my.meila.view.activity;

import android.app.Application;
import android.os.Build;
import android.widget.Toast;

import com.example.my.meila.common.net.NetChangeObserver;
import com.example.my.meila.common.net.NetWorkUtil;
import com.example.my.meila.common.net.NetworkStateReceiver;
import com.example.my.meila.common.utils.AppActivityLifecycleCallbacks;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;


/**
 * Created by My on 2016/10/26.
 */
public class App extends Application {
    private static App app;
    private AppActivityLifecycleCallbacks callbacks;
    private NetChangeObserver observer = new NetChangeObserver() {

        @Override
        public void onConnect(NetWorkUtil.NetType type) {
            super.onConnect(type);
            Toast.makeText(App.this, "官人，我来了", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onDisConnect() {
            super.onDisConnect();
            Toast.makeText(App.this, "官人，不要走", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        //Mob平台授权
        ShareSDK.initSDK(this);
        JPushInterface.setDebugMode(true);
        // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);
        // 初始化 JPush
        app = this;
        registerActivityLifecycleCallbacks();
    }
    public static App getInstance() {
        return app;
    }
    /**
     * 监听网络变化
     */
    private void registerActivityLifecycleCallbacks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && callbacks == null)
            callbacks
                    = new AppActivityLifecycleCallbacks();
        //监听activity的生命周期
        registerActivityLifecycleCallbacks(callbacks);
        //监听网络变化
        registerNetworkStateReceiver();

    }

    public void unRegisterActivityLifecycleCallbacks() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && callbacks != null) {
            unregisterActivityLifecycleCallbacks(callbacks);
        }
    }

    private void registerNetworkStateReceiver() {
        NetworkStateReceiver.registerNetworkStateReceiver(this);
        NetworkStateReceiver.registerObserver(observer);
    }

    public void unRegisterNetworkStateReceiver() {
        if (observer != null) {
            NetworkStateReceiver.removeRegisterObserver(observer);
        }
        NetworkStateReceiver.unRegisterNetworkStateReceiver(this);
    }
}
